/* 单位结构 */
import React, { PureComponent } from 'react';
import {
  Tree,
  Row,
  Col,
  Input,
  InputNumber,
  Form,
  Button,
  Tabs,
  Spin,
  message,
  Cascader,
  Modal,
  Card
} from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { addType, getType, changeType, deleteType } from '@/services/peoples';
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};
class Index extends PureComponent<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      rightLoading: false,
      currentNode: '',
      pid: '',
      title: '',
      num: null,
      level: '',
      treeData: [],
      options: [],
      addPid: '',
      addLevel: '',
      treeLoading: true,
      currentName: '',
      currentNum: '',
      currentLevel: '',
      currentPid: '',
      currentId: '',
      currentLevelEdit:'',
      currentLevelEditValue:[]
    };
  }
  renderType = () => {
    getType().then((res) => {
      if (!res || !res[0]) {
        return this.setState({
          treeLoading:false
        })
      };
      let data = JSON.stringify(res);
      let data2 = JSON.stringify(res);
      data = data.replace(/id/g, 'key').replace(/pkey/g, 'pid');
      data2 = data2
        .replace(/id/g, 'value')
        .replace(/title/g, 'label')
        .replace(/pvalue/g, 'pid');
      this.setState({
        treeData: JSON.parse(data),
        options: JSON.parse(data2),
        treeLoading: false,
      });
    });
  };
  changeTabs = () => {
    this.setState({
      currentNode: '',
      pid: '',
    });
  };
  selectTreeNode = (e: any, node: any) => {
    const { title, key, level, num, pid } = node.node;
    this.setState({
      currentNode: title,
      pid: key,
      level: level,
      currentName: title,
      currentNum: num,
      currentPid: pid,
      currentId: key,
      currentLevel:level,
      currentLevelEditValue:[]
    });
  };
  changeTitleAdd = (e: any) => {
    this.setState({
      title: e.target.value,
    });
  };
  changeNumAdd = (e: any) => {
    this.setState({
      num: e,
    });
  };
  submitAdd = () => {
    const { title, num, addPid, addLevel } = this.state;
    addType({ title, num, pid: addPid||0, level: addLevel ? addLevel + 1 : 1 }).then((res) => {
      if (res.status === 1) {
        this.renderType();
        message.success('添加成功');
      } else {
        message.error('添加失败');
      }
    });
  };
  selectChangeLevelAdd = (e: any, node: any) => {
    const currentnode = node[node.length - 1] || {};
    const { level, value } = currentnode;
    this.setState({
      addPid: value,
      addLevel: level,
    });
  };
  selectChangeLevelEdit = (e: any, node: any) => {
    const currentnode = node[node.length - 1]||{level:'',value:0};
    const { level, value } = currentnode;
    this.setState({
      currentPid: value,
      currentLevelEdit: level,
      currentLevelEditValue:e
    });
  };
  changeCurrentName = (e: any) => {
    this.setState({
      currentName: e.target.value,
    });
  };
  changeCurrentNum = (e: any) => {
    this.setState({
      currentNum: e,
    });
  };
  submitEdit = () => {
    const { currentLevel, currentName, currentPid, currentNum, currentId ,currentLevelEdit} = this.state;
    if(currentPid===currentId)return message.error('操作失败')
    changeType({
      title: currentName,
      num: currentNum,
      pid: currentPid || 0,
      level: String(currentLevelEdit) ? currentLevelEdit+1  : currentLevel,
      id: currentId,
    }).then((res) => {
      if (res.status === 1) {
        message.success('已更新')
        this.renderType()
      } else {
        message.error('更新失败')
      }
    });
  };
  deleteHandle = () => {
    const { currentId } = this.state;
    Modal.confirm({
      title: '提示',
      content: '确定删除该单位？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        deleteType({ id: currentId }).then(res => {
          if (res.status === 1) {
            message.success('已删除')
            this.renderType()
          } else {
            message.error('删除失败')
          }
        });
      },
    });
  };
  componentDidMount() {
    this.renderType();
  }
  componentWillUnmount = () => {
    this.setState = (state, callback) => {
      return;
    };
  }

  render() {
    const {
      rightLoading,
      currentNode,
      treeData,
      treeLoading,
      currentName,
      currentNum,
      options,
      currentId,
      currentLevelEditValue
    } = this.state;
    return (
      <PageContainer>
        <Card>
        <Row gutter={30}>
          <Col span={8} style={{ borderRight: '1px solid #f0f0f0' }}>
            <Spin spinning={treeLoading}>
              <Tree treeData={treeData} onSelect={this.selectTreeNode} />
            </Spin>
          </Col>
          <Col span={16}>
            <Tabs onChange={this.changeTabs}>
              <Tabs.TabPane key="1" tab="添加">
                <Form>
                  <Form.Item {...layout} label="上级">
                    <Cascader
                      options={options}
                      onChange={this.selectChangeLevelAdd}
                      changeOnSelect
                      style={{ width: 300 }}
                      placeholder="请选择上级"
                    />
                  </Form.Item>
                  <Form.Item {...layout} label="名称">
                    <Input
                      style={{ width: 300 }}
                      placeholder="请输入单位/部门名称"
                      onChange={this.changeTitleAdd}
                    />
                  </Form.Item>
                  <Form.Item label="排序" {...layout}>
                    <InputNumber
                      style={{ width: 300 }}
                      placeholder="请输入单位/部门排序"
                      onChange={this.changeNumAdd}
                    />
                  </Form.Item>
                  <Form.Item {...tailLayout}>
                    <Button type="primary" onClick={this.submitAdd}>
                      提交
                    </Button>
                  </Form.Item>
                </Form>
              </Tabs.TabPane>
              {currentId && (
                <React.Fragment>
                  <Tabs.TabPane key="2" tab="修改">
                    <Spin spinning={rightLoading}>
                      <Form>
                        <Form.Item {...layout} label="上级">
                          <Cascader
                            options={options}
                            value={currentLevelEditValue}
                            onChange={this.selectChangeLevelEdit}
                            changeOnSelect
                            style={{ width: 300 }}
                          />
                        </Form.Item>
                        <Form.Item {...layout} label="名称">
                          <Input
                            style={{ width: 300 }}
                            value={currentName}
                            onChange={this.changeCurrentName}
                            placeholder="请输入单位/部门名称"
                          />
                        </Form.Item>
                        <Form.Item label="排序" {...layout}>
                          <InputNumber
                            style={{ width: 300 }}
                            value={currentNum}
                            onChange={this.changeCurrentNum}
                            placeholder="请输入单位/部门排序"
                          />
                        </Form.Item>
                        <Form.Item {...tailLayout}>
                          <Button type="primary" onClick={this.submitEdit}>
                            提交
                          </Button>
                        </Form.Item>
                      </Form>
                    </Spin>
                  </Tabs.TabPane>
                  <Tabs.TabPane key="3" tab="删除">
                    <Button danger onClick={this.deleteHandle}>
                      删除
                    </Button>
                  </Tabs.TabPane>
                </React.Fragment>
              )}
            </Tabs>
          </Col>
        </Row>
        </Card>
      </PageContainer>
    );
  }
}

export default Index;
